package com.kob.backend.controller.user.account;

import cn.hutool.core.io.IoUtil;
import com.kob.backend.utils.SerialPortUtil;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Scanner;

public class SerialCommunication {
    private volatile boolean dataReceived = false;
    private static String receivedData;

    public void performSerialCommunication() throws IOException {
        SerialPortUtil serialPortUtil = SerialPortUtil.getSerialPortUtil();
        ArrayList<String> portNames = serialPortUtil.findPort();

        String portName = "COM3"; // 替换为你要打开的串口名称
        int baudrate = 9600; // 替换为你的波特率
        int databits = SerialPort.DATABITS_8; // 数据位
        int parity = SerialPort.PARITY_NONE; // 校验位
        int stopbits = SerialPort.STOPBITS_1; // 停止位

        SerialPort serialPort = serialPortUtil.openPort(portName, baudrate, databits, parity, stopbits);

        // 添加串口监听器以接收数据
        serialPortUtil.addListener(serialPort, new SerialPortEventListener() {
            @Override
            public void serialEvent(SerialPortEvent event) {
                if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                    try {
                        byte[] bytes = SerialPortUtil.readFromPort(serialPort);
                        receivedData = new String(bytes);
                        dataReceived = true;
//                        System.out.println("receivedData: "+receivedData);

                    } catch (Exception e) {
                    }
                }
            }
        });


        // 等待一段时间以接收数据
        try {
            Thread.sleep(10000000); // 等待10秒
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 检查是否接收到了数据
        if (!dataReceived) {
            System.out.println("No data received.");
        }

        // 最后关闭串口
        serialPortUtil.closePort(serialPort);
    }
    // 提供公共方法供其他类调用获取数据
    public int getReceivedData() {
        try {
            // 将接收到的数据解析为整数
            return Integer.parseInt(receivedData);
        } catch (NumberFormatException e) {
            // 解析失败时返回默认值，你可以根据需要修改这个默认值
            System.out.println("串口接收数据格式错误，返回默认值"+receivedData);
            return 0;
        }
    }
}
